﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using xTeam.HengLe.DataAccess;
using xTeam.HengLe.Entity;
using System.ComponentModel;
using xTeam.Hengle.DataAccess;
using Webdiyer.WebControls.Mvc;

namespace xTeam.HengLe.Controller.Manage
{
    [Authorize]
    public class NewsController : BaseController
    {
        public NewsController()
        {
            _classifyDataAccess = new ClassifyDataAccess(_connectionString);
            // 数据库连接字符串（BaseController获得）
            NewsDataAccess.Con = _connectionString;
        }
        public ActionResult Index()
        {
            return RedirectToAction("List");
        }
        /// <summary>
        /// 检索新闻
        /// </summary>
        /// <param name="tilte">标题</param>
        /// <param name="classifyid">分类编号</param>
        /// <returns>新闻列表</returns>
        public ActionResult List([DefaultValue("")]string tilte, [DefaultValue(0)]int classifyList, int? NewsId)
        {
            ViewData["classifyList"] = GetClassList(classifyList, "所有分类");
            
            // <=0 && <>-2时，标题和分类编号作为条件，分页
            PagedList<ENews> newsPageList = new PagedList<ENews>(NewsDataAccess.GetByCondition(-2, tilte, classifyList), NewsId ?? 1, 10);
            this.ModelState.Remove("NewsId");
            return View(newsPageList);
        }

        /// <summary>
        /// 分类列表
        /// </summary>
        /// <param name="cid">默认选择中项值</param>
        /// <param name="cid">第一项文本</param>
        /// <returns></returns>
        private List<SelectListItem> GetClassList(int cid, string first)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            List<EClassify> classifyList = _classifyDataAccess.GetClassLisytByModuleKey("News", 1);
            // 第一项
            items.Add(new SelectListItem { Text = first, Value = "0" });
            int depth, classifyId;
            string text = string.Empty;

            // 添加项
            foreach (EClassify classify in classifyList)
            {
                text = string.Empty;
                depth = classify.Floor;
                classifyId = classify.ClassifyId;

                // 深度大于1，区分深度
                if (depth > 1)
                {
                    for (int i = 1; i < depth; i++)
                    {
                        text += "----";//──|——|
                    }

                    text += "├";
                }

                text += classify.Title;

                if (cid == classifyId)
                {
                    // 默认选中项
                    items.Add(new SelectListItem { Text = text, Value = classifyId.ToString(), Selected = true });
                }
                else
                {
                    items.Add(new SelectListItem { Text = text, Value = classifyId.ToString() });
                }
            }

            return items;
        }

        /// <summary>
        /// 根据新闻编号获取新闻
        /// </summary>
        /// <param name="newsId">新闻编号</param>
        /// <returns>新闻实体</returns>
        public ActionResult Edit([DefaultValue(0)]int newsId)
        {
            ENews news = new ENews() { Isvalid = true };

            if (newsId > 0)
            {
                // >0时，根据新闻编号获取新闻
                news = NewsDataAccess.GetByCondition(newsId, "", 0)[0];
            }

            ViewData["classifyList"] = GetClassList(news.ClassifyId, "请选择分类");
            this.ModelState.Remove("classifyList");
            return View(news);
        }

        /// <summary>
        /// 添加修改新闻
        /// </summary>
        /// <param name="news">新闻实体</param>
        /// <returns> 新闻编号 </returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(ENews news)
        {
            string msg = string.Empty;

            if (string.IsNullOrEmpty(news.Title))
            {
                msg = "新闻标题不能为空！";
            }
            else if (news.ClassifyId == 0)
            {
                msg = "请选择新闻分类！";
            }
            else if (string.IsNullOrEmpty(news.Contents))
            {
                msg = "新闻内容不能为空！";
            }
            else
            {
                int ret = NewsDataAccess.Edit(news);

                if (ret > 0)
                {
                    msg = "新闻提交成功！";
                    return Content(string.Format("alert('{0}');location.href='" + Url.Action("Edit", "News", new { newsid = ret }) + "';", msg));
                }
                else
                {
                    msg = "新闻提交失败！";
                }
            }

            return Content(string.Format("alert('{0}');", msg));
        }

        /// <summary>
        /// 删除新闻
        /// </summary>
        /// <param name="newsId">新闻编号</param>
        /// <returns> >0时，删除成功 </returns>
        [HttpPost]
        public ActionResult Delete(int newsId)
        {
            // 执行新闻删除
            int ret = NewsDataAccess.Delete(newsId);
            return new EmptyResult();
        }
    }
}
